<template>
    <el-dialog
      v-model="visible"
      title="编辑备件清单"
      width="720px"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div class="tip">计划：{{ plan?.title }}（ID: {{ plan?.id }}）</div>
  
      <!-- 选择备件 -->
      <el-form :model="form" label-width="96px">
        <el-form-item label="选择备件">
          <el-select
            v-model="pickedIds"
            multiple filterable collapse-tags collapse-tags-tooltip
            placeholder="选择需要的备件（可多选）" style="width:100%"
            @change="syncPickedToSpares"
          >
            <el-option v-for="op in spareOptions" :key="op.value" :label="op.label" :value="op.value"/>
          </el-select>
        </el-form-item>
  
        <!-- 已选清单 -->
        <el-form-item label="备件清单">
          <el-table :data="form.spares" border size="small" style="width:100%" empty-text="请先在上方选择备件">
            <el-table-column label="备件" min-width="220">
              <template #default="{ row }">{{ id2name(row.spareId) || row.spareId }}</template>
            </el-table-column>
            <el-table-column label="数量" width="140" align="center">
              <template #default="{ row }">
                <el-input-number v-model="row.qty" :min="1" :max="9999" :step="1" controls-position="right"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <el-button link type="danger" size="small" @click="removeSpare(row.spareId)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
  
      <template #footer>
        <div style="display:flex; justify-content:flex-end; gap:8px;">
          <el-button @click="visible=false">取消</el-button>
          <el-button type="primary" :loading="saving" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, reactive, watch, onMounted } from 'vue'
  import { getPlanSpares, replacePlanSpares } from '@/api/sbtz/mtplan'
  import { listSpare } from '@/api/sbtz/spare'
  
  const props = defineProps({
    modelValue: { type: Boolean, default: false },
    plan: { type: Object, default: () => ({}) } // 需要传入 {id, title, ...}
  })
  const emit = defineEmits(['update:modelValue', 'success'])
  
  const visible = ref(false)
  watch(() => props.modelValue, v => (visible.value = v), { immediate: true })
  watch(visible, v => emit('update:modelValue', v))
  
  // 选项 & 映射
  const spareOptions = ref([])      // [{value,label}]
  const idNameMap = ref(new Map())
  const id2name = (id) => idNameMap.value.get(id)
  
  // 表单
  const form = reactive({
    spares: [] // [{spareId, qty}]
  })
  const pickedIds = ref([])
  
  // 加载所有备件选项
  async function loadSpareOptions() {
    const res = await listSpare({ pageNum:1, pageSize:9999 })
    const rows = res?.rows ?? res?.data?.rows ?? res?.data ?? []
    spareOptions.value = rows.map(r => ({ value: r.id, label: r.name }))
    idNameMap.value = new Map(spareOptions.value.map(x => [x.value, x.label]))
  }
  
  // 加载该计划当前的备件清单
  async function loadPlanSpares() {
    if (!props.plan?.id) return
    const res = await getPlanSpares(props.plan.id)
    // 约定后端返回：[{spareId, qty}]
    const list = res?.data ?? res ?? []
    form.spares = list.map(x => ({ spareId: x.spareId, qty: x.qty ?? 1 }))
    pickedIds.value = form.spares.map(x => x.spareId)
  }
  
  // 同步下拉选择到 spares
  function syncPickedToSpares() {
    const set = new Set(pickedIds.value)
    // 保留仍选中的项
    form.spares = form.spares.filter(it => set.has(it.spareId))
    // 补新增项
    for (const id of set) {
      if (!form.spares.some(it => it.spareId === id)) {
        form.spares.push({ spareId: id, qty: 1 })
      }
    }
  }
  function removeSpare(spareId) {
    pickedIds.value = pickedIds.value.filter(id => id !== spareId)
    form.spares = form.spares.filter(it => it.spareId !== spareId)
  }
  
  watch(() => props.plan?.id, async (id) => {
    if (!id) return
    await Promise.all([loadSpareOptions(), loadPlanSpares()])
  }, { immediate: true })
  
  const saving = ref(false)
  async function save() {
    if (!props.plan?.id) return
    saving.value = true
    try {
      // 空数组表示清空所有备件
      await replacePlanSpares(props.plan.id, form.spares.map(x => ({
        spareId: x.spareId, qty: x.qty || 1
      })))
      visible.value = false
      emit('success') // 通知父级刷新
    } finally {
      saving.value = false
    }
  }
  </script>
  
  <style scoped>
  .tip { margin-bottom: 8px; color: #64748b; font-size: 13px; }
  </style>
  